package com.easwift.qsp.util;

import org.springframework.util.StringUtils;

/**
 * 位操作工具类
 *
 * @author Administrator
 *
 */
public class BitUtils {

	/**
	 * 字节数组转float
	 *
	 * @param bytes
	 * @return
	 */
	public static Float byteArrayToFloat(byte[] bytes) {
		if (bytes.length != 4) {
			return null;
		}
		int[] ints = new int[4];
		for (int i = 0; i < bytes.length; i++) {
			ints[i] = Byte.toUnsignedInt(bytes[i]);
		}
		int inte = (ints[0] << 24) + (ints[1] << 16) + (ints[2] << 8) + ints[3];
		return Float.intBitsToFloat(inte);
	}

	/**
	 * 字节数组转成16进制表示格式的字符串
	 *
	 * @param byteArray
	 *            需要转换的字节数组
	 * @return 16进制表示格式的字符串
	 **/
	public static String toHexString(byte[] byteArray) {
		if (byteArray == null || byteArray.length < 1)
			throw new IllegalArgumentException("this byteArray must not be null or empty");

		final StringBuilder hexString = new StringBuilder();
		for (int i = 0; i < byteArray.length; i++) {
			if ((byteArray[i] & 0xff) < 0x10)//0~F前面不零
				hexString.append("0");
			hexString.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return hexString.toString().toLowerCase();
	}


	/**
	 * 字节数组转16进制字符串
	 *
	 * @param bytes
	 * @return
	 */
	public static String byteArrayToHexString(byte[] bytes) {
		StringBuffer buffer = new StringBuffer();
		for (byte b : bytes) {
			if (b < 0) {
				buffer.append(Integer.toHexString(256 + b));
			} else if (b < 16) {
				buffer.append("0" + Integer.toHexString(b));
			} else {
				buffer.append(Integer.toHexString(b));
			}
		}
		return buffer.toString();
	}

	/**
	 * 16进制字符串转字节数组
	 *
	 * @param bytes
	 * @return
	 */
	public static byte[] hexStringToByteArray(String string) {
		if (!StringUtils.isEmpty(string)) {
			byte[] bytes = new byte[string.length() / 2];
			for (int i = 0; i < string.length() / 2 * 2; i += 2) {
				String hex = string.substring(i, i + 2);
				bytes[i / 2] = (byte) Short.parseShort(hex, 16);
			}
			return bytes;
		}
		return null;
	}

	/**
	 * 翻转数组
	 *
	 * @param src
	 * @return
	 */
	public static byte[] reverseArray(byte[] src) {
		byte[] des = new byte[src.length];
		for (int i = 0; i < src.length; i++) {
			des[i] = src[src.length - 1 - i];
		}
		return des;
	}


}
